package org.topic.surpermarket;

import org.topic.discount.DiscountStrategy;
import org.topic.discount.NoDiscount;
import org.topic.user.ShoopingCart;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 超市类
 */
public class SuperMarket {

    private List<Product> productList; // 超市商品列表

    private DiscountStrategy discountStrategy; // 超市当前折扣策略

    /**
     * 超市构造函数
     */
    public SuperMarket() {
        productList = new ArrayList<>();
        discountStrategy = new NoDiscount(); // 默认无折扣
    }

    /**
     * 添加商品
     * @param product
     */
    public void addProduct(Product product) {
        if (product == null) {
            throw new IllegalArgumentException("商品不能为null");
        }
        productList.add(product);
    }

    /**
     * 获取超市当前所有商品
     * @return 不可修改的商品列表
     */
    public List<Product> getAllProducts() {
        return new ArrayList<>(productList);
    }

    /**
     * 设置超市折扣策略
     * @param strategy 折扣策略
     */
    public void setDiscountStrategy(DiscountStrategy strategy) {
        if (strategy == null) {
            throw new IllegalArgumentException("折扣策略不能为null");
        }
        this.discountStrategy = strategy;
    }

    /**
     * 结账
     * @param cart 购物车
     * @return 最终价格
     */
    public BigDecimal checkout(ShoopingCart cart) {
        if (cart == null) {
            throw new IllegalArgumentException("购物车不能为null");
        }


        BigDecimal subtotal = cart.calculateSubtotal();
        return discountStrategy.applyDiscount(subtotal, cart);
    }

    /**
     * 打印小票
     * @param cart
     */
    public void printReceipt(ShoopingCart cart) {
        if (cart == null) {
            throw new IllegalArgumentException("购物车不能为null");
        }

        System.out.println("============ 购物明细 ============");
        StringBuilder receiptStr = new StringBuilder();
        cart.getItems().forEach((product, quantity) -> {
            System.out.printf("%s: %d斤 × %.2f元 = %.2f元",
                    product.getName(), quantity, product.getPrice().stripTrailingZeros(),
                    product.calculatePrice(quantity));
            System.out.println();
        });

        BigDecimal subtotal = cart.calculateSubtotal();
        BigDecimal total = checkout(cart);

        System.out.println("-------------------------------");
        System.out.printf("小计: %.2f元\n", subtotal.stripTrailingZeros());

        if (subtotal.compareTo(total) > 0) {
            System.out.printf("优惠: %.2f元\n", subtotal.subtract(total).stripTrailingZeros());
        }

        System.out.println("-------------------------------");
        System.out.printf("总计: %.2f元\n", total.stripTrailingZeros());
        System.out.println("===============================");
    }
}
